﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace CommonManagement
{
    /// <summary>
    /// 反馈应用服务类
    /// </summary>
    public class FeedbackAppService : ApplicationService, IFeedbackAppService
    {
        private readonly IAuthManager _authManager;
        private readonly FeedbackManager _feedbackManager;
        private readonly IRepository<Feedback, int> _feedbackRepository;

        public FeedbackAppService(
            IAuthManager authManager,
            FeedbackManager feedbackManager,
            IRepository<Feedback, int> feedbackRepository)
        {
            _authManager = authManager;
            _feedbackManager = feedbackManager;
            _feedbackRepository = feedbackRepository;
        }

        // 新增
        public async Task<ActionResponse> CreateAsync(CreateFeedbackDto input)
        {
            // 读取用户Id
            var userId = _authManager.GetUserId();
            // 新增
            await _feedbackManager.CreateAsync(
                userId,
                input.AppType,
                input.Title,
                input.Content);
            // 返回结果
            return ActionResponse.Successful();
        }

        // 分页列表
        public async Task<ListResponse<FeedbackDto>> PagedListAsync(
            PagedListRequest request,
            string title)
        {
            // 查询
            var query = await _feedbackRepository.GetQueryableAsync();
            query = query.WhereIf(!string.IsNullOrWhiteSpace(title), m => m.Title.Contains(title));
            // 计数
            var count = query.Count();
            // 排序
            if(!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Feedback>, List<FeedbackDto>>(list);
            return ListResponse<FeedbackDto>.Successful(count, dtos);
        }

        // 详情
        public async Task<ResultResponse<FeedbackDto>> GetAsync(int id)
        {
            var entity = await _feedbackRepository.GetAsync(id);
            var dto = ObjectMapper.Map<Feedback, FeedbackDto>(entity);
            return ResultResponse<FeedbackDto>.Successful(dto);
        }
    }
}